// 二次封装axios
import axios from "axios";
import { Message } from "element-ui";
import router from "@/router";
import Nprogress from 'nprogress'

// 引入环境地址
import envConfig from "./env.js";

// 创建axios实例
const service = axios.create({
  baseURL: envConfig.prodEnv.baseURL, // timeout: 5000
});



// 设置请求拦截器
service.interceptors.request.use(
  (config) => {
     //开始加载进度条
     Nprogress.start()
    if (sessionStorage.getItem("token")) {
      config.headers.Authorization = sessionStorage.getItem("token");
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 请求响应拦截器
service.interceptors.response.use(
  (res) => {
    //成功返回结束加载进度条
    Nprogress.done()
    const {
      meta: { msg, status: code },
      data: result,
    } = res.data;
    const successStatusArr = [200, 201, 204];
    if (successStatusArr.includes(code)) {
      // 如果是登录成功,则将后台返回的token保存到本地
      if (res.config.url === "/login") {
        sessionStorage.setItem("token", result.token);
        router.push("/home");
      } // 成功的提示
      Message.success(msg); // 返回成功后的数据
      return result
    }
    Message.error(msg);
    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default service;
